<!--
    /**
     * 调用示例：
     * <tree-select :height="400" // 下拉框中树形高度
     *              :width="200" // 下拉框中树形宽度
     *              size="small"  // 输入框的尺寸: medium/small/mini
     *              :data="data" // 树结构的数据
     *              v-model="" //绑定值
     *              :defaultProps="defaultProps" // 树结构的props
     *              multiple   // 多选
     *              showFilter // 是否过滤
     *              clearable   // 可清空选择
     *              collapseTags   // 多选时将选中值按文字的形式展示
     *              checkStrictly // 多选时，严格遵循父子不互相关联
     *              :nodeKey="nodeKey"   // 绑定nodeKey，默认绑定'departmentCode'
     *              :checkedKeys="defaultCheckedKeys"  // 传递默认选中的节点key组成的数组 作废
     *              @popoverHide="popoverHide"> // 事件有两个参数：第一个是所有选中的节点ID，第二个是所有选中的节点数据
     *              </tree-select>
     */
-->
<template>
  <div>
    <div class="mask" v-show="isShowSelect" @click="isShowSelect = !isShowSelect"></div>
    <el-popover
placement="bottom-start" :width="width" trigger="manual"
                v-model="isShowSelect" @hide="popoverHide">
      <el-input v-if="showFilter" placeholder="输入关键字进行过滤" v-model="filterText" clearable> </el-input>
      <el-tree
class="common-tree" :style="style" ref="tree" :data="list" :props="defaultProps"
               :show-checkbox="multiple"
               :node-key="nodeKey"
               :check-strictly="checkStrictly"
               default-expand-all
               :filter-node-method="filterNode"
               :expand-on-click-node="false"
               :check-on-click-node="multiple"
               :highlight-current="true"
               @node-click="handleNodeClick"
               @check-change="handleCheckChange"></el-tree>
      <el-select
                 :style="selectStyle" slot="reference" ref="select" :size="size"
                 v-model="selectedData"
                 :multiple="multiple"
                 :clearable="clearable"
                 :collapse-tags="collapseTags"
                 @click.native="isShowSelect = !isShowSelect"
                 @remove-tag="removeSelectedNodes"
                 @clear="removeSelectedNode"
                 @change="changeSelectedNodes"
                 class="tree-select">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
    </el-popover>
  </div>
</template>

<script>
import depart from '@/api/system/dempartmentAPI'
export default {
  name: 'tree-select',
  model: {
    prop: 'bindData',
    event: 'select'
  },
  props: {
    // 树结构数据
    data: {
      type: Array,
      default () {
        return []
      }
    },
    hiddenChildren: [String],
    bindData: {
      type: [String, Array]
    },
    defaultProps: {
      type: Object,
      default () {
        return {
          children: 'childrenList',
          label: 'departmentName'
        }
      }
    },
    // 配置是否可多选
    multiple: {
      type: Boolean,
      default () {
        return false
      }
    },
    // 配置是否可清空选择
    clearable: {
      type: Boolean,
      default () {
        return false
      }
    },
    showFilter: {
      type: Boolean,
      default: false
    },
    // 配置多选时是否将选中值按文字的形式展示
    collapseTags: {
      type: Boolean,
      default () {
        return false
      }
    },
    disabledData: {
      type: Array,
      default () {
        return []
      }
    },
    nodeKey: {
      type: String,
      default () {
        return 'departmentCode'
      }
    },
    // 显示复选框情况下，是否严格遵循父子不互相关联
    checkStrictly: {
      type: Boolean,
      default () {
        return false
      }
    },
    // 默认选中的节点key数组
    // checkedKeys: {
    //   type: Array,
    //   default () {
    //     return []
    //   }
    // },
    size: {
      type: String,
      default () {
        return 'small'
      }
    },
    width: {
      type: Number,
      default () {
        return 280
      }
    },
    height: {
      type: Number,
      default () {
        return 200
      }
    }

  },
  data () {
    return {
      list: [],
      isAutoLoadData: true, // 是否自动获取
      isShowSelect: false, // 是否显示树状选择器
      options: [],
      selectedData: [], // 选中的节点
      style: 'height:' + this.height + 'px;',
      selectStyle: 'width:' + (this.width) + 'px;',
      checkedIds: [],
      checkedData: [],
      filterText: '',
      checkedTempKeys: []
    }
  },
  mounted () {
    if (this.isAutoLoadData) {
      this.queryData({departmentCode: '1', deep: true}).then(res => {
        this.setHiddenChildren(res)
        this.setNodeDisabled(res)
        this.list = res
        this.$nextTick(() => {
          this.initCheckedData()
        })
      })
    }
  },
  methods: {
    queryData (params) {
      return new Promise(async (resolve, reject) => {
        await depart.getDepartmentListAPI(params).then(res => {
          resolve(res.data || [])
        })
      })
    },
    setHiddenChildren (list) {
      if (this.hiddenChildren) {
        list.map(v => {
          const value = v[this.nodeKey]
          if (value === this.hiddenChildren) {
            v[this.defaultProps.children] = []
          } else {
            const children = v[this.defaultProps.children]
            if (children && children.length > 0) {
              this.setHiddenChildren(children)
            }
          }
        })
      }
    },
    setNodeDisabled (list) {
      if (this.multiple && list && this.disabledData.length > 0) {
        list.map(v => {
          const value = v[this.nodeKey]
          if (this.disabledData.includes(value)) {
            v.disabled = true
          }
          const children = v[this.defaultProps.children]
          if (children && children.length > 0) {
            this.setNodeDisabled(children)
          }
        })
      }
    },
    // 单选时点击tree节点，设置select选项
    setSelectOption (node) {
      let tmpMap = {}
      tmpMap.value = node.key
      tmpMap.label = node.label
      this.options = []
      this.options.push(tmpMap)
      this.selectedData = node.key
    },
    // 单选，选中传进来的节点
    checkSelectedNode (checkedKeys) {
      var item = checkedKeys[0]
      this.$refs.tree.setCurrentKey(item)
      var node = this.$refs.tree.getNode(item)
      this.setSelectOption(node)
    },
    // 多选，勾选上传进来的节点
    checkSelectedNodes (checkedKeys) {
      this.$refs.tree.setCheckedKeys(checkedKeys)
    },
    // 单选，清空选中
    clearSelectedNode () {
      this.selectedData = ''
      this.$emit('select', null)
      this.$refs.tree.setCurrentKey(null)
    },
    // 多选，清空所有勾选
    clearSelectedNodes () {
      var checkedKeys = this.$refs.tree.getCheckedKeys() // 所有被选中的节点的 key 所组成的数组数据
      for (let i = 0; i < checkedKeys.length; i++) {
        this.$refs.tree.setChecked(checkedKeys[i], false)
      }
    },
    initCheckedData () {
      if (this.multiple) {
        // 多选
        if (this.checkedTempKeys.length > 0) {
          this.checkSelectedNodes(this.checkedTempKeys)
        } else {
          this.clearSelectedNodes()
        }
      } else {
        // 单选
        if (this.checkedTempKeys.length > 0) {
          this.checkSelectedNode(this.checkedTempKeys)
        } else {
          this.clearSelectedNode()
        }
      }
    },
    popoverHide () {
      if (this.multiple) {
        this.checkedIds = this.$refs.tree.getCheckedKeys() // 所有被选中的节点的 key 所组成的数组数据
        this.checkedData = this.$refs.tree.getCheckedNodes() // 所有被选中的节点所组成的数组数据
      } else {
        this.checkedIds = this.$refs.tree.getCurrentKey()
        this.checkedData = this.$refs.tree.getCurrentNode()
      }
      this.$emit('select', this.checkedIds && this.checkedIds.length > 0 ? this.checkedIds : null)
      this.$emit('popoverHide', this.checkedIds, this.checkedData)
    },
    // 单选，节点被点击时的回调,返回被点击的节点数据
    handleNodeClick (data, node) {
      if (!this.multiple) {
        this.setSelectOption(node)
        this.isShowSelect = !this.isShowSelect
        this.$emit('change', this.selectedData)
      }
    },
    // 多选，节点勾选状态发生变化时的回调
    handleCheckChange () {
      var checkedKeys = this.$refs.tree.getCheckedKeys() // 所有被选中的节点的 key 所组成的数组数据
      this.options = checkedKeys.map((item) => {
        var node = this.$refs.tree.getNode(item) // 所有被选中的节点对应的node
        let tmpMap = {}
        tmpMap.value = node.key
        tmpMap.label = node.label
        return tmpMap
      })
      this.selectedData = this.options.map((item) => {
        return item.value
      })
      this.$emit('select', this.selectedData && this.selectedData.length > 0 ? this.selectedData : null)
      this.$emit('change', this.selectedData)
    },
    // 多选,删除任一select选项的回调
    removeSelectedNodes (val) {
      this.$refs.tree.setChecked(val, false)
      var node = this.$refs.tree.getNode(val)
      if (!this.checkStrictly && node.childNodes.length > 0) {
        this.treeToList(node).map(item => {
          if (item.childNodes.length <= 0) {
            this.$refs.tree.setChecked(item, false)
          }
        })
        this.handleCheckChange()
      }
      this.$emit('change', this.selectedData)
    },
    treeToList (tree) {
      var queen = []
      var out = []
      queen = queen.concat(tree)
      while (queen.length) {
        var first = queen.shift()
        if (first.childNodes) {
          queen = queen.concat(first.childNodes)
        }
        out.push(first)
      }
      return out
    },
    // 单选,清空select输入框的回调
    removeSelectedNode () {
      this.clearSelectedNode()
      this.$emit('change', this.selectedData)
    },
    // 选中的select选项改变的回调
    changeSelectedNodes (selectedData) {
      // 多选,清空select输入框时，清除树勾选
      if (this.multiple && selectedData.length <= 0) {
        this.clearSelectedNodes()
      }
      this.$emit('change', this.selectedData)
    },
    filterNode (value, data) {
      if (!value) return true
      return data[this.defaultProps.label].indexOf(value) !== -1
    }
  },
  watch: {
    data: {
      handler (val) {
        if (val && Array.isArray(val) && val.length > 0) {
          this.isAutoLoadData = false
        }
        this.list = val || []
      },
      immediate: true,
      deep: true
    },
    isShowSelect (val) {
      // 隐藏select自带的下拉框
      this.$refs.select.blur()
    },
    filterText (val) {
      this.$refs.tree.filter(val)
    },
    bindData: {
      handler (val) {
        if (!val) return
        if (Array.isArray(val)) {
          this.checkedTempKeys = val
        } else {
          this.checkedTempKeys = [val]
        }
        // this.initCheckedData()
      },
      immediate: true
    }
    // checkedKeys (val) {
    //   if (!val) return
    //   this.checkedTempKeys = val
    //   // this.initCheckedData()
    // }
  }
}
</script>

<style lang="scss" scoped>
  .mask{
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    opacity: 0;
    z-index: 11;
  }
  .common-tree{
    overflow: auto;
  }
  .tree-select{
    z-index: 111;
  }
  >>>.el-input--small .el-input__inner {
    height: 40px;
    line-height: 40px;
}
</style>
